<?php
/**
 * Created by PhpStorm.
 * User: yuliang
 * Date: 2017/6/5
 * Time: 下午5:02
 */

namespace app\admin\controller;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Controller;

class Teacher extends Controller
{
    // 教师详情
    public function teacherDetail(){
        $id = input('post.id');
        $info = model('Teacher')->field(true)->where('id',$id)->find();
        if(empty($info)){
            return api_error('30007','该教师不存在！');
        }else{
            $info['education'] = json_decode($info['education']);
            $info['age'] = birthday($info['birth']);
            return api_return('操作成功！',$info);
        }
    }

    // 教师列表
    public function teacherList(){
        $page = input('page')?input('page'):1;
        $pageSize = 10;
        $search = input('search');
        if(trim($search)){
            $teacher = model('Teacher')->where('name|academy|education','like','%'.$search.'%')->page($page,$pageSize)->order('id asc')->select();
            $count = model('Teacher')->where('name|academy|education','like','%'.$search.'%')->count();
        }else{
            $teacher = model('Teacher')->page($page,$pageSize)->select();
            $count = model('Teacher')->count();
        }
        if(!empty($teacher)){
            foreach ($teacher as &$value){
                $value['education'] = json_decode($value['education']);
                $value['age'] = birthday($value['birth']);
            }
        }
        $data['page'] = ceil($count/$pageSize);
        $data['data'] = $teacher;
        return api_return('操作成功！',$data);
    }

    // 添加老师
    public function add(){
//        $array = array(
//            array('education'=> '本科','academy' => '清华大学'),
//            array('education'=> '硕士','academy' => '北京大学'),
//        );
//        echo json_encode($array);die;
        $data = input('post.');
        $image = '';
        $validate = $this->validate($data,'Teacher.add');
        if(true !== $validate){
            return api_error('1000',$validate);
        }
        // 图片处理
        $avatarFile = request()->file('avatar');
        $imageFile = request()->file('image');
        if($avatarFile){
            $avatarFile = $avatarFile->getInfo();
            $fileInfo = pathinfo($avatarFile['name']);
            $ext = 'jpg';
            if(isset($fileInfo['extension'])){
                $ext = $fileInfo['extension'];
            }
            $file = $avatarFile['tmp_name'];
            $qiniu = config('qiniu');
            $auth = new Auth($qiniu['access_key'],$qiniu['secret_key']);
            $token = $auth->uploadToken($qiniu['bucket']);
            // 构建 UploadManager 对象
            $uploadMgr = new UploadManager();
            $fileName = 'upload/teacher/'.date('Ymd').'/'.md5(rand(1000,9999)).'.'.$ext;
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token,$fileName,$file);
            if($err !== null){
                return api_error('30001',$err['code'].$err['error']);
            }else{
                $avatar = $qiniu['site_url'].$ret['key'];
            }
        }else{
            return api_error('1000','请选择图片');
        }
        // 上传宣传图
        if($imageFile){
            $imageFile = $imageFile->getInfo();
            $fileInfo = pathinfo($imageFile['name']);
            $ext = 'jpg';
            if(isset($fileInfo['extension'])){
                $ext = $fileInfo['extension'];
            }
            $file = $imageFile['tmp_name'];
            $token = $auth->uploadToken($qiniu['bucket']);
            // 构建 UploadManager 对象
            $uploadMgr = new UploadManager();
            $fileName = 'upload/teacher/'.date('Ymd').'/'.md5(rand(1000,9999)).'_image.'.$ext;
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token,$fileName,$file);
            if($err !== null){
                return api_error('30002',$err['code'].$err['error']);
            }else{
                $image = $qiniu['site_url'].$ret['key'];
            }
        }
        $data['image'] = $image;
        $data['avatar'] = $avatar;
//        $data['education'] = json_encode(input('post.education'));
        $result = model('Teacher')->isUpdate(false)->allowField(true)->save($data);
        if($result){
            return api_return('添加教师成功！',array());
        }else{
            return api_return('30003','添加教师失败！');
        }

    }

    // 修改资料
    public function edit(){
        $data = input('post.');
        $validate = $this->validate($data,'Teacher.edit');
        if(true !== $validate){
            return api_error('1000',$validate);
        }
        // 图片处理
        $avatarFile = request()->file('avatar');
        $imageFile = request()->file('image');
        if($avatarFile){
            $avatarFile = $avatarFile->getInfo();
            $fileInfo = pathinfo($avatarFile['name']);
            $ext = 'jpg';
            if(isset($fileInfo['extension'])){
                $ext = $fileInfo['extension'];
            }
            $file = $avatarFile['tmp_name'];
            $qiniu = config('qiniu');
            $auth = new Auth($qiniu['access_key'],$qiniu['secret_key']);
            $token = $auth->uploadToken($qiniu['bucket']);
            // 构建 UploadManager 对象
            $uploadMgr = new UploadManager();
            $fileName = 'upload/teacher/'.date('Ymd').'/'.md5(rand(1000,9999)).'.'.$ext;
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token,$fileName,$file);
            if($err !== null){
                return api_error('30004',$err['code'].$err['error']);
            }else{
                $avatar = $qiniu['site_url'].$ret['key'];
            }
            $data['avatar'] = $avatar;
        }
        // 上传宣传图
        if($imageFile){
            $imageFile = $imageFile->getInfo();
            $fileInfo = pathinfo($imageFile['name']);
            $ext = 'jpg';
            if(isset($fileInfo['extension'])){
                $ext = $fileInfo['extension'];
            }
            $file = $imageFile['tmp_name'];
            $qiniu = config('qiniu');
            $auth = new Auth($qiniu['access_key'],$qiniu['secret_key']);
            $token = $auth->uploadToken($qiniu['bucket']);
            // 构建 UploadManager 对象
            $uploadMgr = new UploadManager();
            $fileName = 'upload/teacher/'.date('Ymd').'/'.md5(rand(1000,9999)).'_image.'.$ext;
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token,$fileName,$file);
            if($err !== null){
                return api_error('30005',$err['code'].$err['error']);
            }else{
                $image = $qiniu['site_url'].$ret['key'];
            }
            $data['image'] = $image;
        }
//        $data['education'] = json_encode(input('post.education'));
        $result = model('Teacher')->isUpdate(true)->allowField(true)->save($data,['id'=>$data['id']]);
        if($result !== false){
            return api_return('修改教师成功！',array());
        }else{
            return api_return('30005','修改教师失败！');
        }
    }

    // 操作上下线
    public function operate(){
        $data['id'] = trim(input('post.id'),',');
        $data['status'] = input('post.status');
        $rule = [
            'id' => 'require',
            'status' => 'require|in:0,-1,1'
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $where['id'] = ['in',$data['id']];
        $result = model('Teacher')->isUpdate(true)->save(['status'=>$data['status']],$where);
        if($result !== false){
            return api_return('修改状态成功！',array());
        }else{
            return api_error('30006','修改失败！');
        }
    }

    // 删除操作
    public function delTeacher(){
        $data['id'] = trim(input('post.id'),',');
        $rule = [
            'id' => 'require',
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $where['id'] = ['in',$data['id']];
        $result = model('Teacher')->isUpdate(true)->save(['status'=> '-1'],$where);
        if($result !== false){
            return api_return('删除成功！',array());
        }else{
            return api_error('30007','删除失败！');
        }
    }

    // 根据学科分类教师
    public function sortTeacher(){
        $array = [
            '1' => '数学',
            '2' => '逻辑',
            '3' => '作文',
            '4' => '英语'
        ];
        $model = model('Teacher');
        $list = [];
        foreach ($array as $key=>$value){
            $list[$key]['name'] = $value;
            $list[$key]['data'] = $model->field('id,name')->where('status',1)->where("FIND_IN_SET($key,type)")->select();
        }
        return api_return('操作成功！',$list);
    }

    // 教师申请列表
    public function applyList(){
        $page = input('page')?input('page'):1;
        $pageSize = 10;
        $model = model('TeacherApply');
        $count = $model->count();
        $data['data'] = $model->page($page,$pageSize)->order('create_time desc')->select();
        $data['page'] = ceil($count/$pageSize);
        return api_return('操作成功！',$data);
    }

    // 申请详情
    public function applyDetail(){
        $id = input('post.id');
        $data = model('TeacherApply')->where(['id'=>$id])->find();
        if(!empty($data)){
            return api_return('操作成功！',$data);
        }else{
            return api_error('30008','对不起，该条记录不存在！');
        }
    }

    // 教师申请审核
    public function audit(){
        $id = input('post.id');
        $status = input('post.status');
        $reason = input('post.reason')?input('post.reason'):'';

        $model = model('TeacherApply');
        $info = $model->field('id,id_card,diploma,status,reason,audit_time,create_time,update_time',true)->where(['id'=>$id])->find()->toArray();
        if(empty($info)){
            return api_error('30008','对不起，该条记录不存在！');
        }

        $data['status'] = $status;
        $data['audit_time'] = date('Y-m-d H:i:s',time());
        // 审核成功，写入教师表中
        if($status == 1){
            $result = $model->save($data,['id'=>$id]);
            if($result !== false){
                $info['avatar'] = '';
                $info['image'] = '';
                $info['description'] = '';
                $info['status'] = 0;
                $result1 = model('Teacher')->save($info);
                if($result1){
                    return api_return('操作成功！',array());
                }else{
                    return api_error('30011','对不起，写入教师表失败！');
                }
            }
        }else if($status == -1){
            $data['reason'] = $reason;
            $result = $model->save($data,['id'=>$id]);
        }else{
            return api_error('30010','无效的操作！');
        }
        if($result !== false){
            return api_return('操作成功！',array());
        }else{
            return api_error('30009','对不起，操作失败！');
        }
    }
}